import { Inject, Injectable } from '@nestjs/common';
import { CreateBianhuantuDto } from './dto/create-bianhuantu.dto';
import { UpdateBianhuantuDto } from './dto/update-bianhuantu.dto';
import { PagesDto } from '../dto/pages.dto';
import { Repository } from 'typeorm';
import { BianhuantuEntity } from './entities/bianhuantu.entity';

@Injectable()
export class BianhuantuService {
  constructor(
    @Inject('BIANHUANTU_REPOSITORY')
    private bianhuantuRepository: Repository<BianhuantuEntity>,
  ) {}

  async create(createBianhuantuDto: CreateBianhuantuDto) {
    try {
      const newItem = this.bianhuantuRepository.create(createBianhuantuDto);
      return await this.bianhuantuRepository.save(newItem);
    } catch (error) {
      console.error('创建失败:', error);
      throw new Error('数据库操作异常');
    }
  }

  async findAll() {
    return await this.bianhuantuRepository.find();
  }

  async findAllPage(pages: PagesDto) {
    const { page = 1, limit = 10 } = pages;
    const skip = (page - 1) * limit;

    const [list, total] = await this.bianhuantuRepository.findAndCount({
      skip,
      take: limit,
      order: { createTime: 'DESC' }, // 添加默认排序
    });

    return {
      list,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async findOne(id: number) {
    return await this.bianhuantuRepository.findOne({
      where: { id },
      // 可添加关联查询 relations: ['relatedEntity']
    });
  }

  async update(id: number, updateBianhuantuDto: UpdateBianhuantuDto) {
    await this.bianhuantuRepository.update(id, updateBianhuantuDto);
    return this.findOne(id); // 返回更新后的完整对象
  }

  async remove(id: number) {
    const result = await this.bianhuantuRepository.delete(id);
    return { affected: result.affected };
  }

  // 可选：添加批量删除方法
  async batchRemove(ids: number[]) {
    const result = await this.bianhuantuRepository
      .createQueryBuilder()
      .delete()
      .whereInIds(ids)
      .execute();

    return { affected: result.affected };
  }
}
